package com.web.handler.service;

import com.web.accumulate.entity.AccumulateTransaction;
import com.web.accumulate.service.AccumulateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.web.config.RabbitConfig;
import com.web.handler.entity.ProviderTransaction;
import com.web.position.entity.Position;
import com.web.transaction.entity.Transaction;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ProviderTransactionService {

	@Autowired
	private RabbitConfig rabbitConfig;

	@Autowired
	private AccumulateService accumulateService;

	public Transaction convertToTransaction(ProviderTransaction fxd) {
		Transaction t = new Transaction();
		t.setTradeDate(fxd.getTradeDate());
		t.setValueDate(fxd.getTradeDate());
		//t.setExcde(fxd.getExcde());
		t.setExcde(fxd.getCurrency1().trim()+fxd.getCurrency2().trim());
		t.setCustomerNo(fxd.getCustomerNo());
		if(Transaction.TX_BUY.equals(fxd.getBuySell())) {
			t.setWithdrawalAcct(fxd.getAccountNo2());
			t.setWithdrawalCcy(fxd.getCurrency2());
			t.setWithdrawalAmt(fxd.getAmount2());
			t.setDepositeAcct(fxd.getAccountNo1());
			t.setDepositeCcy(fxd.getCurrency1());
			t.setDepositedAmt(fxd.getAmount1());
		}
		if(Transaction.TX_SELL.equals(fxd.getBuySell())) {
			t.setWithdrawalAcct(fxd.getAccountNo1());
			t.setWithdrawalCcy(fxd.getCurrency1());
			t.setWithdrawalAmt(fxd.getAmount1());
			t.setDepositeAcct(fxd.getAccountNo2());
			t.setDepositeCcy(fxd.getCurrency2());
			t.setDepositedAmt(fxd.getAmount2());
		}
		t.setBankCostRate(fxd.getBankCostRate());
		t.setSrcJnlNo(fxd.getSrcJnlNo());
		return t;
	}

	public void callCore(List<Position> list){
		for (Position position : list) {
			rabbitConfig.sendCore(position);
		}
	}

	public void uploadToAccumulated(Transaction transaction){
		AccumulateTransaction at = new AccumulateTransaction();
		at.setTradeDate(transaction.getTradeDate());
		at.setCurrency(transaction.getWithdrawalCcy());
		at.setBuySellOption(Transaction.TX_BUY);
		List<AccumulateTransaction> buyAmtList = accumulateService.getAccumulateTransactions(at);
		at.setCurrency(transaction.getDepositeCcy());
		at.setBuySellOption(Transaction.TX_SELL);
		List<AccumulateTransaction> sellAmtList = accumulateService.getAccumulateTransactions(at);

		List<AccumulateTransaction> amtList = Stream.concat(buyAmtList.stream(), sellAmtList.stream())
				.collect(Collectors.toList());

		for (AccumulateTransaction accumulateTransaction : amtList) {
			rabbitConfig.sendAccumulated(accumulateTransaction);
		}

	}
}
